package com.cloud.workTest;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Base64;

public class MicrosoftTOTP {

    // 生成随机的密钥
    public static String generateSecretKey() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[20];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes);
    }

    // 生成OTP认证URL
    public static String getOtpAuthURL(String account, String secretKey, String issuer) throws UnsupportedEncodingException {
        String Url = "otpauth://totp/"
                + URLEncoder.encode((!StringUtils.isEmpty(issuer) ? (issuer + ":") : "") + account, "UTF-8").replace("+", "%20")
                + "?secret=" + URLEncoder.encode(secretKey, "UTF-8").replace("+", "%20")
                + (!StringUtils.isEmpty(issuer) ? ("&issuer=" + URLEncoder.encode(issuer, "UTF-8").replace("+", "%20")) : "");
        //log.info(Url);
        return Url;
    }

    // 生成二维码图像
    public static BufferedImage generateQRCodeImage(String barcodeText) throws WriterException {
        QRCodeWriter barcodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);

        BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < 200; y++) {
            for (int x = 0; x < 200; x++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }
        return image;
    }


    // 校验TOTP代码
    public static int generateTOTP(String secretKey) {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        return gAuth.getTotpPassword(secretKey, System.currentTimeMillis());
    }


    public static void main(String[] args) throws IOException, WriterException {
        GoogleAuthenticatorKey googleAuthenticatorKey = TotpGeneratorTest.generateTotpKey();
        String secretKey = googleAuthenticatorKey.getKey();
        System.out.println("secretKey " + secretKey);
        BufferedImage bufferedImage = generateQRCodeImage(getOtpAuthURL("1287625911@qq.com", secretKey, "jzt"));
        ImageIO.write(bufferedImage, "png", new File("C:\\Users\\86159\\Pictures\\Camera Roll\\qr.jpg"));

    }


}
